import hashlib

import scrapy
from ..items import MyFileItem
import re


class Spider (scrapy.Spider):
    name = 'lawphi_jurpd'
    allowed_domains = ['lawphil.net/judjuris/']
    # 菲律宾法律体系数据库地址
    start_urls = ['https://lawphil.net/judjuris/judjuris.html']
    id = 0

    # 解析初始页面
    def parse(self, response):
        # 获得个年份成员列表
        trs = response.xpath('//*[@colspan="2"]//*/tr[@bgcolor="#fbedfa"]/td')
        for tr in trs:
            # 各模块网址
            yearUrlS = tr.xpath('./a/@href')
            if len(yearUrlS):
                yeara = tr.xpath('./a')[0]
                yield response.follow(yeara, callback=self.yearparse, dont_filter=True)

    # 解析年份成员列表页
    def yearparse(self, response):
        # 获得个年份月份列表
        trs = response.xpath('//*[@colspan="2"]//*/tr[@bgcolor="#fbedfa"]/td')
        for tr in trs:
            # 各模块网址
            mothUrlS = tr.xpath('./a/@href')
            if len(mothUrlS):
                motha = tr.xpath('./a')[0]
                yield response.follow(motha, callback=self.mothparse, dont_filter=True)

    # 解析月份成员列表页
    def mothparse(self, response):
        # 获得成员列表
        trs = response.xpath('//*[@colspan="2"]//*/tr[@valign="top"]')
        for tr in trs:
            # 判例编号
            LawNoS = tr.xpath('./td[1]/a/text()')
            LawNo = ''
            if len(LawNoS):
                for LawNoSl in LawNoS:
                    LawNo = LawNo + ' ' + LawNoSl.get().strip()
                LawNo = re.sub(r'''^ *''', r'''''', LawNo)  # 去除开头的空格

            # 裁决日期
            cDateS = tr.xpath('./td[1]/text()')
            cDate = ''
            if len(cDateS):
                for cDateSl in cDateS:
                    cDate = cDate + ' ' + cDateSl.get().strip()
                cDate = re.sub(r'''^ *''', r'''''', cDate)  # 去除开头的空格
            # 标题
            titleS = tr.xpath('./td[2]//text()')
            title = ''
            if len(titleS):
                for titleSl in titleS:
                    title = title + ' ' + titleSl.get().strip()
                title = re.sub(r'''^ *''', r'''''', title)  # 去除开头的空格
                title = re.sub(r'''"''', r"'", title)  # 将双引号变为单引号
            # 详细网址
            detailUrlS = tr.xpath('./td[1]/a/@href')
            if len(detailUrlS):
                a = tr.xpath('./td[1]/a')[0]
                detailUrl = 'https://' + self.allowed_domains[0] + detailUrlS.get().strip()
                yield response.follow(a, callback=self.detailed, dont_filter=True,
                                      meta={'LawNo': LawNo, 'detailUrl': detailUrl,
                                            'cDate': cDate, 'title': title})
            else:
                detailUrlS = tr.xpath('./td[3]/a/@href')
                if len(detailUrlS):
                    a = tr.xpath('./td[3]/a')[0]
                    yield response.follow(a, callback=self.detailurled, dont_filter=True,
                                          meta={'LawNo': LawNo,
                                                'cDate': cDate, 'title': title})

    # 解析详情页
    def detailed(self, response):
        item = MyFileItem()
        if response.status == 200:
            # 法律详细网址
            detailUrl = response.url
            # 案例编号
            LawNo = response.meta['LawNo']
            # 裁决日期
            cDate = response.meta['cDate']

            country = 'Philippines'
            website = 'lawphil'
            modular = 'jurpd'
            # 下载文件格式
            ext = 'pdf'

            # 下载文件名
            fina = ''
            if len(detailUrl) > 0:
                fina = 'f' + str(hashlib.md5(detailUrl.encode('utf-8')).hexdigest())
            # 标题名
            titlel = response.meta['title']
            title = re.sub(r'''"''', r"'", titlel)  # 修改双引号为单引号
            # 原文内容
            htmlsS = response.xpath('//blockquote')
            if len(htmlsS) > 0:
                htmls = htmlsS.get().strip()
                # 唯一ID
                systemid = str(hashlib.md5(detailUrl.encode('utf-8')).hexdigest())

                item['file_urls'] = ''
                item['country'] = country
                item['website'] = website
                item['modular'] = modular
                item['ext'] = ext
                item['fina'] = fina
                item['title'] = ''
                item['abstractUrl'] = ''
                item['abstract'] = ''
                item['dabstractUrl'] = ''
                item['detail'] = htmls
                item['detailUrl'] = ''
                item['downloadUrl'] = ''

                item['Title'] = title
                item['CaseNumber'] = LawNo
                item['KeyWord'] = ''
                item['SortA'] = 'LAWCOUNTRYFLB'
                item['People'] = ''
                item['CaseOfAction'] = ''
                item['UseLaw'] = ''
                item['AdjudicationDate'] = cDate
                item['FullText'] = ''
                item['JudgAgency'] = ''
                item['SortB'] = 'LANGUAGEYY'
                item['SortC'] = ''
                item['CaseSummary'] = ''
                item['Articles'] = ''
                item['Chapter'] = ''
                item['Section'] = ''
                item['SYS_FLD_DIGITFILENAME'] = fina
                item['FileUrl'] = ''
                item['AbstractFileName'] = ''
                item['DownLoadUrl'] = detailUrl
                item['DownLoadWebNameC'] = '菲律宾法律和法律体系数据库'
                item['DownLoadWebNameE'] = "PHILIPPINE LAWS AND JURISPRUDENCE DATABANK"
                item['SYSID'] = systemid
                item['Website'] = 'Jurisprudence'
                item['Isconversion'] = '1'
                item['CaseDate'] = ''

                yield item

    # 解析详情页
    def detailurled(self, response):
        item = MyFileItem()
        if response.status == 200:

            # 法律详细网址
            detailUrl = response.url
            # 案例编号
            LawNo = response.meta['LawNo']
            # 裁决日期
            cDate = response.meta['cDate']

            country = 'Philippines'
            website = 'lawphil'
            modular = 'jurpd'
            # 下载文件格式
            ext = 'pdf'

            # 下载文件名
            fina = ''
            if len(detailUrl) > 0:
                fina = 'f' + str(hashlib.md5(detailUrl.encode('utf-8')).hexdigest())
            # 标题名
            titlel = response.meta['title']
            title = re.sub(r'''"''', r"'", titlel)  # 修改双引号为单引号

            # 唯一ID
            systemid = str(hashlib.md5(detailUrl.encode('utf-8')).hexdigest())

            item['file_urls'] = ''
            item['country'] = country
            item['website'] = website
            item['modular'] = modular
            item['ext'] = ext
            item['fina'] = fina
            item['title'] = ''
            item['abstractUrl'] = ''
            item['abstract'] = ''
            item['dabstractUrl'] = ''
            item['detail'] = ''
            item['detailUrl'] = ''
            item['downloadUrl'] = detailUrl

            item['Title'] = title
            item['CaseNumber'] = LawNo
            item['KeyWord'] = ''
            item['SortA'] = 'LAWCOUNTRYFLB'
            item['People'] = ''
            item['CaseOfAction'] = ''
            item['UseLaw'] = ''
            item['AdjudicationDate'] = cDate
            item['FullText'] = ''
            item['JudgAgency'] = ''
            item['SortB'] = 'LANGUAGEYY'
            item['SortC'] = ''
            item['CaseSummary'] = ''
            item['Articles'] = ''
            item['Chapter'] = ''
            item['Section'] = ''
            item['SYS_FLD_DIGITFILENAME'] = fina
            item['FileUrl'] = ''
            item['AbstractFileName'] = ''
            item['DownLoadUrl'] = detailUrl
            item['DownLoadWebNameC'] = '菲律宾法律和法律体系数据库'
            item['DownLoadWebNameE'] = "PHILIPPINE LAWS AND JURISPRUDENCE DATABANK"
            item['SYSID'] = systemid
            item['Website'] = 'Jurisprudence'
            item['Isconversion'] = '0'
            item['CaseDate'] = ''

            yield item

